package com.zzyl.oss;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.DeleteObjectsRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

@Component
public class AliyunOSSOperator {
    @Autowired
    private AliyunOSSProperties aliYun;
    @Autowired
    OSS ossClient;

    /**
     * 上传文件
     *
     * @return
     */
    public String store(String originalFilename, byte[] bytes) throws Exception {
        // 通过Properties从环境变量中获取访问凭证
        CredentialsProvider credentialsProvider = getCredentialsProvider();

        // 填写Object完整路径，完整路径中不能包含Bucket名称
        LocalDate now = LocalDate.now();
        String path = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String name = UUID.randomUUID().toString();

        // 获取上传的文件名后缀
        String[] split = originalFilename.split("\\.");
        String objectName = path + "/" + name + "." + split[split.length - 1];
//        String objectName = path + name + "." + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create().endpoint(aliYun.getEndpoint()).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();

        try {
            // 上传文件。
            ossClient.putObject(aliYun.getBucketName(), objectName, new ByteArrayInputStream(bytes));
        } finally {
            ossClient.shutdown();
        }
        String[] strings = aliYun.getEndpoint().split("//");

        return "https://" +
                aliYun.getBucketName() +
                "." +
                strings[strings.length - 1] +
                "/" +
                objectName;
    }

    public CredentialsProvider getCredentialsProvider() throws IOException {
        Properties properties = new Properties();

        // 读取配置文件
        FileInputStream input = new FileInputStream(aliYun.getConfigFilePath());
        properties.load(input);
        input.close();

        // 从配置文件中获取AK和SK
        String accessKeyId = properties.getProperty("alibaba_cloud_access_key_id");
        String accessKeySecret = properties.getProperty("alibaba_cloud_access_key_secret");

        return new DefaultCredentialProvider(accessKeyId, accessKeySecret);
    }

    /**
     * 根据url删除文件
     *
     * @param pathUrl url地址（全路径）
     */
    public void delete(String pathUrl) {
        String prefix = "https://" + aliYun.getBucketName() + "." + aliYun.getEndpoint() + "/";
        String key = pathUrl.replace(prefix, "");
        List<String> keys = new ArrayList<>();
        keys.add(key);
        // 删除Objects
        ossClient.deleteObjects(new DeleteObjectsRequest(aliYun.getBucketName()).withKeys(keys));

    }
}
